package com.mingtu.guards.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClipboardUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.activity.ResetPasswordActivity;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.activity.LoginActivity;
import com.mingtu.common.activity.WebActivity;
import com.mingtu.common.base.BaseActivity;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.bean.UpdateBean;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.room.ReportedEvent;
import com.mingtu.common.room.ReportedEventDao;
import com.mingtu.common.room.TrackEvent;
import com.mingtu.common.room.TrackEventDao;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.HProgressDialogUtils;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.guards.R;
import com.mingtu.guards.base.Application;
import com.mingtu.guards.room.SignInEvent;
import com.mingtu.guards.room.SignInEventDao;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.utils.MySPTools;
import com.mingtu.uploadevent.bean.UploadFileResultBean;
import com.mingtu.uploadevent.callback.UploadCallback;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.qcloud.tuicore.TUILogin;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate._XUpdate;
import com.xuexiang.xupdate.service.OnFileDownloadListener;
import com.xuexiang.xutil.app.PathUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.ups.JPushUPSManager;
import okhttp3.OkHttpClient;

public class MySetActivity extends BaseActivity {

    @BindView(R.id.layout_reset_password)
    RelativeLayout layoutResetPassword;
    @BindView(R.id.button_exit)
    Button buttonExit;
    @BindView(R.id.tv_version_name)
    TextView tvVersionName;
    @BindView(R.id.tip_view)
    View tipView;
    @BindView(R.id.layout_version)
    RelativeLayout layoutVersion;
    @BindView(R.id.tv_registration_id)
    TextView tvRegistrationId;
    @BindView(R.id.layout_registration_id)
    RelativeLayout layoutRegistrationId;
    @BindView(R.id.layout_policy)
    RelativeLayout layoutPolicy;
    @BindView(R.id.layout_sign_out)
    RelativeLayout layoutSignOut;
    @BindView(R.id.offline_tip_view)
    View offlineTipView;
    @BindView(R.id.layout_offline)
    RelativeLayout layoutOffline;
    private Timer timer;
    private boolean versionFlag = false;
    private String downloadUrl;
    private String registrationID;
    private ReportedEventDao reportedEventDao;
    private SignInEventDao signInEventDao;
    private TrackEventDao trackEventDao;

    private List<ReportedEvent> reportedEventList = new ArrayList<>();
    private List<SignInEvent> signInEventList = new ArrayList<>();
    private List<TrackEvent> trackEventList = new ArrayList<>();
    private LoadingPopupView uploadPopup;
    private OkHttpClient.Builder builder;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 200:
                    ReportedEvent reportedEvent = (ReportedEvent) msg.obj;
                    int id = reportedEvent.getId();
                    String address = reportedEvent.getAddress();
                    String lat = reportedEvent.getLat();
                    String lng = reportedEvent.getLng();
                    String memo = reportedEvent.getMemo();
                    String tag = reportedEvent.getTag();
                    String uploadType = reportedEvent.getUploadType();
                    String createTime = reportedEvent.getCreateTime();
                    String myCreateTime = MyUtills.stampToDateTime2(createTime);
                    ArrayList<LinkedHashMap<String, Object>> picVideoArray = reportedEvent.getPicVideoArray();

                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("address", address);
                    hashMap.put("lat", lat);
                    hashMap.put("lng", lng);
                    hashMap.put("eventDesc", memo);
                    if (!StringUtils.isEmpty(tag)) {
                        hashMap.put("tag", tag);
                    }
                    hashMap.put("attachVOS", picVideoArray);
                    hashMap.put("type", uploadType);
                    hashMap.put("createTime", myCreateTime);
                    String str = GsonUtils.toJson(hashMap);


                    OkGo.<String>post(Constant.getInstance().POST_UPLOAD_EVENT)
                            .tag(this)
                            .upJson(str)
                            .execute(new StringDialogCallback(ActivityUtil.getTopActivity()) {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    String result = response.body();
                                    if (!StringUtils.isEmpty(result)) {
                                        JSONObject jsonObject = JSON.parseObject(result);
                                        String msg = jsonObject.getString("msg");
                                        if (msg.equals(Constant.RESULT_SUCCESS)) {
                                            reportedEventDao.deleteEvent(id);
                                            EventBus.getDefault().post(new MyEventBus(Constant.getInstance().REFRESH_MY_REPORT_DATA));
                                            reportedEventList = reportedEventDao.getAll();
                                            if (reportedEventList.size() == 0) {
                                                if (uploadPopup != null) {
                                                    uploadPopup.dismiss();
                                                    ToastUtils.showLong(getResources().getString(R.string.text_upload_success));
                                                }
                                            }
                                        } else {
                                            MyLogUtil.e("BaseActivity", "离线的数据上传失败");
                                        }

                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    String result = response.body();
                                    MyLogUtil.e(getClass().getSimpleName(), "离线的数据上传失败");
                                }
                            });


                    break;


                case 300:
                    SignInEvent signInEvent = (SignInEvent) msg.obj;
                    int signInEventId = signInEvent.getId();
                    String mylat = signInEvent.getLat();
                    String mylng = signInEvent.getLng();
                    String content = signInEvent.getContent();
                    String clockTime = signInEvent.getClockTime();
                    ArrayList<LinkedHashMap<String, Object>> myPicVideoArray = signInEvent.getPicVideoArray();

                    HashMap<String, Object> myHashMap = new HashMap<>();
                    myHashMap.put("lnglat", mylng + "," + mylat);
                    myHashMap.put("content", content);
                    myHashMap.put("taskClockAttachVOList", myPicVideoArray);
                    myHashMap.put("clockTime", clockTime);
                    String mystr = GsonUtils.toJson(myHashMap);

                    OkGo.<String>post(MyConstant.getInstance().POST_CLOCK_TASK)
                            .tag(this)
                            .upJson(mystr)
                            .execute(new StringDialogCallback(ActivityUtil.getTopActivity()) {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    String result = response.body();
                                    if (!StringUtils.isEmpty(result)) {
                                        JSONObject jsonObject = JSON.parseObject(result);
                                        String msg = jsonObject.getString("msg");
                                        if (msg.equals(Constant.RESULT_SUCCESS)) {
                                            signInEventDao.deleteEvent(signInEventId);
                                            EventBus.getDefault().post(new MyEventBus(MyConstant.getInstance().REFRESH_MY_SIGN_IN_DATA));
                                            signInEventList = signInEventDao.getAll();
                                            if (signInEventList.size() == 0) {
                                                if (uploadPopup != null) {
                                                    uploadPopup.dismiss();
                                                    ToastUtils.showLong(getResources().getString(R.string.text_upload_success));
                                                }
                                            }
                                        } else {
                                            MyLogUtil.e("BaseActivity", "离线的数据上传失败");
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    String result = response.body();
                                    MyLogUtil.e(getClass().getSimpleName(), "离线的数据上传失败");
                                }
                            });


                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.activity_set;
    }

    @Override
    protected void initView() {
        setModuleTitle("账号设置");
    }

    @Override
    protected void initData() {
        String versionName = AppUtils.getAppVersionName();
        if (!StringUtils.isEmpty(versionName)) {
            tvVersionName.setText("v" + versionName);
        }

        registrationID = JPushInterface.getRegistrationID(this);
        if (!StringUtils.isEmpty(registrationID)) {
            layoutRegistrationId.setVisibility(View.VISIBLE);
            tvRegistrationId.setText(registrationID);
        } else {
            layoutRegistrationId.setVisibility(View.GONE);
        }

        boolean isPublish = Constant.getInstance().IS_PUBLISH;
        if (isPublish) {
            layoutPolicy.setVisibility(View.VISIBLE);
            layoutSignOut.setVisibility(View.VISIBLE);
        } else {
            layoutPolicy.setVisibility(View.GONE);
            layoutSignOut.setVisibility(View.GONE);
        }
    }

    @Override
    protected void getData() {
        getVersionInfo();
    }


    @OnClick({R.id.layout_reset_password, R.id.button_exit, R.id.layout_version,
            R.id.layout_registration_id, R.id.layout_policy, R.id.layout_sign_out, R.id.layout_offline})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_reset_password:
                IntentUtils.getInstance().readyGo(this, ResetPasswordActivity.class);
                break;
            case R.id.layout_registration_id:
                ClipboardUtils.copyText(registrationID);
                ToastUtils.showLong("已经复制到剪切板");
                break;

            case R.id.button_exit:
                new XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .dismissOnTouchOutside(true)
                        .hasShadowBg(true)
                        .asConfirm(context.getResources().getString(R.string.text_tip), "是否退出登录？",
                                context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        logout();
                                    }
                                }, null, false)
                        .show();
                break;

            case R.id.layout_version:
                if (versionFlag) {
                    //下载安装APK
                    XXPermissions.with(this)
                            // 不适配 Android 11 可以这样写
                            .permission(Permission.Group.STORAGE)
                            // 适配 Android 11 需要这样写，这里无需再写 Permission.Group.STORAGE
//                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE) || permissions.contains(Permission.READ_EXTERNAL_STORAGE)) {
                                        installAPK();
                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    if (never) {
                                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                        new XPopup.Builder(MySetActivity.this)
                                                .isDestroyOnDismiss(true)
                                                .dismissOnTouchOutside(true)
                                                .hasShadowBg(true)
                                                .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_storage_auth),
                                                        context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                                        new OnConfirmListener() {
                                                            @Override
                                                            public void onConfirm() {
                                                                XXPermissions.startPermissionActivity(MySetActivity.this, permissions);
                                                            }
                                                        }, null, false)
                                                .show();
                                    }
                                }
                            });

                } else {
                    ToastUtils.showLong("已经是最新版本");
                }
                break;

            case R.id.layout_policy:
                Bundle bundle = new Bundle();
                bundle.putString("title", "隐私政策");
                bundle.putString("url", Constant.getInstance().getURL_PRIVACY());
                IntentUtils.getInstance().readyGo(MySetActivity.this, WebActivity.class, bundle);
                break;
            case R.id.layout_sign_out:
                new XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .dismissOnTouchOutside(true)
                        .hasShadowBg(true)
                        .asConfirm(context.getResources().getString(R.string.text_tip), "是否注销账号？",
                                context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        logout();
                                    }
                                }, null, false)
                        .show();
                break;
            case R.id.layout_offline:
                offlineEvent();
                break;
        }
    }

    private void offlineEvent() {
        if (netWorkState) {
            //离线上报
            reportedEventDao = BaseApplication.getBaseApplication().getReportedEventDao();
            if (reportedEventDao != null) {
                reportedEventList = reportedEventDao.getAll();
                if (reportedEventList.size() > 0) {
                    uploadReport();
                }
            }

            //离线签到
            signInEventDao = Application.getApplication().getSignInEventDao();
            if (signInEventDao != null) {
                signInEventList = signInEventDao.getAll();
                if (signInEventList.size() > 0) {
                    uploadSignInData();
                }
            }


            //离线巡护数据
            trackEventDao = BaseApplication.getBaseApplication().getTrackEventDao();
            trackEventList = trackEventDao.getAll();
            if (trackEventList.size() > 0) {
                uploadTrackData();
            }

            if (reportedEventList.size() > 0 || signInEventList.size() > 0 || trackEventList.size() > 0) {
                uploadPopup = (LoadingPopupView) new XPopup.Builder(this)
                        .dismissOnBackPressed(true)
                        .dismissOnTouchOutside(false)
                        .isLightNavigationBar(true)
                        .isDarkTheme(false)
                        .asLoading("数据上传中...", LoadingPopupView.Style.ProgressBar)
                        .show();
            } else {
                ToastUtils.showLong("暂无离线数据哦~");
            }

        } else {
            ToastUtils.showLong(getResources().getString(R.string.text_no_net));
        }
    }

    private void installAPK() {
        if (StringUtils.isEmpty(downloadUrl)) {
            ToastUtils.showLong("下载文件获取有误！");
            return;
        }
        XUpdate.newBuild(this)
                .apkCacheDir(PathUtils.getExtDownloadsPath()) //设置下载缓存的根目录
                .build()
                .download(downloadUrl, new OnFileDownloadListener() {   //设置下载的地址和下载的监听
                    @Override
                    public void onStart() {
                        HProgressDialogUtils.showHorizontalProgressDialog(MySetActivity.this, "下载进度", false);
                    }

                    @Override
                    public void onProgress(float progress, long total) {
                        HProgressDialogUtils.setProgress(Math.round(progress * 100));
                    }

                    @Override
                    public boolean onCompleted(File file) {
                        HProgressDialogUtils.cancel();
                        tipView.setVisibility(View.GONE);
                        versionFlag = false;
                        MyLogUtil.e("apk", "apk下载完毕，文件路径：" + file.getPath());
                        _XUpdate.startInstallApk(MySetActivity.this, file); //填写文件所在的路径

                        return false;
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        HProgressDialogUtils.cancel();
//                                    tipView.setVisibility(View.VISIBLE);
//                                    versionFlag = true;
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }

        if (builder != null) {
            OkGo.getInstance().cancelTag(builder.build(), this);
        }
    }

    @Override
    protected void onResume() {
        getVersionInfo();
        super.onResume();
    }


    /**
     * 退出登录
     */
    private void logout() {
        if (netWorkState) {

            OkGo.<String>post(Constant.getInstance().POST_LOGOUT)
                    .tag(this)
                    .upJson("")
                    .execute(new StringDialogCallback(this) {
                        @Override
                        public void onSuccess(Response<String> response) {
                            String result = response.body();
                            if (!StringUtils.isEmpty(result)) {
                                JSONObject jsonObject = JSON.parseObject(result);
                                String msg = jsonObject.getString("msg");
                                if (msg.equals(Constant.RESULT_SUCCESS)) {
                                    SPStaticUtils.remove(SPTools.token);
                                    ToastUtils.showLong("退出成功！");
                                    //实例化Timer类 ,守护线程，不在后台一直运行
                                    TUILogin.logout(new V2TIMCallback() {
                                        @Override
                                        public void onSuccess() {
                                            MyLogUtil.e("TUILogin", "TUILogin  logout =====onSuccess=====");
                                            SPStaticUtils.remove(MySPTools.TUI_CALLING);
                                        }

                                        @Override
                                        public void onError(int code, String desc) {
                                            MyLogUtil.e("TUILogin", "TUILogin  logout ======onError====");

                                        }
                                    });


//                                业务场景
//                                客户端 App 支持多帐户登录。
//                                每个用户登录时，都把该帐号 UID 设置为别名，从而接收到该用户的推送消息。
//                                但有个问题：A 退出登录后，B 还未更新设置别名之前的发给 A 的推送消息，会被 B 收到。

//                                问题解析
//                                别名是与本设备（本应用）绑定的。在 B 未设置别名成功之前，推送给 A 的信息都一直会被收到。

//                                解决思路
//                                A 用户注销前，先做一个别名设置：把别名设置为空。
//                                这样发给 A 的推送，将不会再给到本设置。
//                                  此接口只能清除当前设备与目标 alias 的绑定关系，如果你想清除目标 alias 与所有设备的绑定关系，请调 服务器删除接口
                                    JPushInterface.deleteAlias(context, Constant.TYPE_BIND_ALIAS);
                                    JPushUPSManager.turnOffPush(context, null);
//                                timer = new Timer(true);
//                                timer.schedule(new TimerTask() {
//                                    public void run() {
                                    IntentUtils.getInstance().readyGo(MySetActivity.this, LoginActivity.class);
                                    ActivityUtil.clearActivity();
//                                    }
//                                }, Constant.TIMER_TIME);

                                } else {
                                    ToastUtils.showLong("退出失败！");
                                }
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            String result = response.body();
                            MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                        }
                    });
        } else {
            SPStaticUtils.remove(SPTools.token);
            IntentUtils.getInstance().readyGo(MySetActivity.this, LoginActivity.class);
            ActivityUtil.clearActivity();
        }
    }

    /**
     * 获取版本信息
     */
    private void getVersionInfo() {
        OkGo.<String>get(Constant.getInstance().GET_UPDATE)
                .tag(this)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            UpdateBean updateBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                updateBean = new UpdateBean();
                                updateBean = gson.fromJson(result, UpdateBean.class);
                                downloadUrl = updateBean.getDownloadUrl();
                                int currentVersion = AppUtils.getAppVersionCode();
                                String versionCode = updateBean.getVersionCode();
                                if (!StringUtils.isEmpty(versionCode)) {
                                    if (currentVersion < Integer.parseInt(versionCode)) { //当前版本小于远程版本提示更新
                                        tipView.setVisibility(View.VISIBLE);
                                        versionFlag = true;
                                    }
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }


    /**
     * 连接网络之后上传上报信息
     *
     * @param
     * @return
     */

    private void uploadReport() {
        if (netWorkState && reportedEventList.size() > 0) {
            for (int i = 0; i < reportedEventList.size(); i++) {
                ArrayList<LinkedHashMap<String, Object>> picVideoArray = new ArrayList<>();
                ReportedEvent reportedEvent = reportedEventList.get(i);
                List<ReportedEvent.MyattachVOSBean> myattachVOSBeans = reportedEvent.getMyattachVOS();
                int size = myattachVOSBeans.size();
                for (int j = 0; j < size; j++) {
                    ReportedEvent.MyattachVOSBean myattachVOSBean = myattachVOSBeans.get(j);
                    String pathName = myattachVOSBean.getPathName();
                    String type = myattachVOSBean.getType();       //type : 1: 第一张照片 ,2 第二张照片 ，3 视频,

                    ArrayList<File> files = new ArrayList<>();
                    File file = new File(pathName);
                    files.add(file);
                    uploadFile(files, new UploadCallback() {
                        @Override
                        public void result(List<UploadFileResultBean.DataBean.UrlBean> urlBeans) {
                            if (urlBeans != null) {
                                int size = urlBeans.size();
                                if (size > 0) {
                                    for (int i = 0; i < size; i++) {
                                        String url = urlBeans.get(i).getUrl();
                                        LinkedHashMap picVidoInfo = new LinkedHashMap<>();
                                        picVidoInfo.put("type", type);
                                        picVidoInfo.put("url", url);
                                        picVideoArray.add(picVidoInfo);

                                        if (myattachVOSBeans.size() == picVideoArray.size()) {
                                            reportedEvent.setPicVideoArray(picVideoArray); //将上传的数据传到handler中
                                            Message message = Message.obtain();
                                            message.obj = reportedEvent;
                                            message.what = 200;
                                            handler.sendMessage(message);
                                        }
                                    }
                                }
                            }
                        }
                    });

                }
            }
        }
    }

    private void uploadSignInData() {
        if (netWorkState && signInEventList.size() > 0) {
            for (int i = 0; i < signInEventList.size(); i++) {
                ArrayList<LinkedHashMap<String, Object>> picVideoArray = new ArrayList<>();
                SignInEvent signInEvent = signInEventList.get(i);
                List<SignInEvent.MyattachVOSBean> myattachVOSBeans = signInEvent.getMyattachVOS();
                int size = myattachVOSBeans.size();
                for (int j = 0; j < size; j++) {
                    SignInEvent.MyattachVOSBean myattachVOSBean = myattachVOSBeans.get(j);
                    String pathName = myattachVOSBean.getPathName();
                    ArrayList<File> files = new ArrayList<>();
                    File file = new File(pathName);
                    files.add(file);
                    uploadFile(files, new UploadCallback() {
                        @Override
                        public void result(List<UploadFileResultBean.DataBean.UrlBean> urlBeans) {
                            if (urlBeans != null) {
                                int size = urlBeans.size();
                                if (size > 0) {
                                    for (int i = 0; i < size; i++) {
                                        String url = urlBeans.get(i).getUrl();
                                        LinkedHashMap picVidoInfo = new LinkedHashMap<>();
                                        picVidoInfo.put("url", url);
                                        picVideoArray.add(picVidoInfo);

                                        if (myattachVOSBeans.size() == picVideoArray.size()) {
                                            signInEvent.setPicVideoArray(picVideoArray); //将上传的数据传到handler中
                                            Message message = Message.obtain();
                                            message.obj = signInEvent;
                                            message.what = 300;
                                            handler.sendMessage(message);
                                        }
                                    }
                                }
                            }
                        }
                    });

                }
            }
        }

    }

    /**
     * 连接网络之后上传巡护信息
     *
     * @param
     * @return
     */

    private void uploadTrackData() {
        if (netWorkState && trackEventList.size() > 0) {
            for (int i = 0; i < trackEventList.size(); i++) {
                TrackEvent trackEvent = trackEventList.get(i);
                int id = trackEvent.getId();
                String duration = trackEvent.getDuration();
                String beginTime = trackEvent.getBeginTime();
                String endTime = trackEvent.getEndTime();
                String mileage = trackEvent.getMileage();
                String dataList = trackEvent.getDataList();
                double validMileage = trackEvent.getValidMileage();  //有效里程
                ArrayList<String> myAreaList = trackEvent.getAreaList();
                List<HashMap<String, Object>> myTaskPointsEntities = trackEvent.getTaskPointsEntities();

                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("beginTime", beginTime);
                hashMap.put("endTime", endTime);
                hashMap.put("duration", duration);
                hashMap.put("mileage", mileage);
                hashMap.put("validMileage", validMileage);
                hashMap.put("dataList", dataList);
                hashMap.put("areaList", myAreaList);
                hashMap.put("taskPointsEntities", myTaskPointsEntities);
                String str = GsonUtils.toJson(hashMap);

                OkGo.<String>post(Constant.getInstance().POST_UPLOAD_TASK)
                        .tag(this)
                        .upJson(str)
                        .execute(new StringDialogCallback(this) {
                            @Override
                            public void onSuccess(Response<String> response) {
                                String result = response.body();
                                if (!StringUtils.isEmpty(result)) {
                                    JSONObject jsonObject = JSON.parseObject(result);
                                    String msg = jsonObject.getString("msg");
                                    if (msg.equals(Constant.RESULT_SUCCESS)) {
                                        trackEventDao.deleteEvent(id);
                                        EventBus.getDefault().post(new MyEventBus(Constant.REFRESH_MY_TRACK_DATA));
                                        trackEventList = trackEventDao.getAll();
                                        if (trackEventList.size() == 0) {
                                            if (uploadPopup != null) {
                                                uploadPopup.dismiss();
                                                ToastUtils.showLong(getResources().getString(R.string.text_upload_success));
                                            }
                                        }
                                    } else {
                                        MyLogUtil.e("BaseActivity", "离线的数据上传失败");
                                    }

                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                String result = response.body();
                                MyLogUtil.e(getClass().getSimpleName(), "离线的数据上传失败");
                            }
                        });


            }

        }

    }


    /**
     * 上传图片、视频(目前接口只支持单张上传，要支持多张上传的话需要更改逻辑)
     */
    private void uploadFile(ArrayList<File> files, final UploadCallback uploadCallback) {
        builder = new OkHttpClient.Builder();
        builder.addInterceptor(BaseApplication.getHttpLoggingInterceptor());
        builder.readTimeout(5 * 1000, TimeUnit.MILLISECONDS);      //读取超时时间
        builder.writeTimeout(5 * 1000, TimeUnit.MILLISECONDS);     //写入超时时间
        builder.connectTimeout(5 * 1000, TimeUnit.MILLISECONDS);   //连接超时时间

        OkGo.<String>post(Constant.getInstance().POST_UPLOAD_FILE)
                .tag(this)
                .client(builder.build())
                .retryCount(1)
                .addFileParams("files", files)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            UploadFileResultBean resultBean = new UploadFileResultBean();
                            resultBean = gson.fromJson(result, UploadFileResultBean.class);
                            List<UploadFileResultBean.DataBean.UrlBean> urlBeans = resultBean.getData().getUrl();
                            uploadCallback.result(urlBeans);
                        } else {
                            uploadCallback.result(null);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                        uploadCallback.result(null);
                        if (uploadPopup != null) {
                            uploadPopup.dismiss();
                            ToastUtils.showLong(getResources().getString(R.string.text_check_net));
                        }
                    }
                });
    }
}